<template>
  <!-- 隐患排查 -->
  <div class="hiddendangercheck">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        v-model="form"
        ref="crud"
        @search-change="searchChange"
        @search-reset="searchReset"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
      >

        <!-- 现场照片表格自定义 -->
        <template slot="xczp" slot-scope="scope">
          <div class="ope_row_div">
            <span v-if="scope.row['xczp'] === '' || scope.row['xczpFileList'].length === 0">-</span>
            <el-button 
              v-else 
              type="text" 
              icon="el-icon-picture-outline" 
              size="mini" 
              @click="handleViewPhoto(scope.row)">
              查看
            </el-button>
          </div>
        </template>

        <!-- 相关附件表格自定义 -->
        <template slot="zgxgfjFile" slot-scope="scope">
          <div class="enclosure_div">
            <a :href="downloadHead + scope.row['zgxgfjFile'].id" v-if="scope.row['zgxgfjFile'].id !== '' && scope.row['zgxgfjFile'].id !== undefined">
              <i class="el-icon-download"></i>下载
            </a>
            <span v-else>-</span>
          </div>
        </template>

        <!-- 排查设置表格自定义 -->
        <template slot="setting" slot-scope="scope">
          <div>
            <el-button
              type="success"
              size="mini"
              @click="handleSetting(scope.row)">
              排查设置
            </el-button>
          </div>
        </template>

        <!-- 排查结果表格自定义 -->
        <template slot="result" slot-scope="scope">
          <div>
            <el-button
              type="primary"
              size="mini"
              @click="handleResult(scope.row)">
              排查结果
            </el-button>
          </div>
        </template>

        <!-- 整改设置表格自定义 -->
        <template slot="improve" slot-scope="scope">
          <div>
            <el-button
              v-if="scope.row['jcjl'] === '3'"
              type="warning"
              size="mini"
              @click="handleImprove(scope.row)">
              整改设置
            </el-button>
            <span v-else>-</span>
          </div>
        </template>

      </avue-crud>

      <!-- 弹窗：图片 -->
      <viewpicture 
        :localPicBox="localPicBox" 
        :localPictures="localPictures" 
        :viewPicTitle="viewPicTitle" 
        @confirmViewPicture="confirmViewPicture" 
        @handleClosePicBox="handleClosePicBox">
      </viewpicture>

      <!-- 弹窗：选择检查项目 -->
      <chooseCheckItems 
        :checkItemDialog="checkItemDialog"
        :selectedCheckItems="selectedCheckItems"
        @confirmChooseCheckItems="confirmChooseCheckItems"
        @closeCheckItemDialog="closeCheckItemDialog">
      </chooseCheckItems>

      <!-- 弹窗：排查设置 -->
      <el-dialog 
        title="排查设置"
        append-to-body
        :visible.sync="settingDialog"
        :close-on-click-modal="false" 
        :before-close="closeSettingDialog"
        width="60%"
        class="setting_dialog"
      > 
        <avue-form 
          ref="settingForm" 
          v-model="settingObj" 
          :option="settingOption" 
          @submit="confirmSetting"
        >
          <template slot="jcxm">
            <el-button 
              size="small"
              type="success"
              @click="handleCheck()">
              选择检查项目
            </el-button>
          </template>
          <template slot="jcxmTags">
            <div class="selected_tag_container">
              <el-tag
                v-for="(tag, index) in selectedTags"
                :key="index"
                size="medium"
                closable
                :disable-transitions="false"
                @close="closeSelectedItems(index)" >
                {{tag.jcxm}}
              </el-tag>
            </div>
          </template>
          <template slot="menuForm">
            <el-button 
              size="small"
              icon="el-icon-close"
              @click="closeSettingDialog()">
              取 消
            </el-button>
          </template>
        </avue-form>

      </el-dialog>

      <!-- 弹窗：排查结果 -->
      <el-dialog 
        :title="dialogTitle"
        append-to-body
        :visible.sync="resultImproveDialog"
        :close-on-click-modal="false" 
        :before-close="closeResultImproveDialog"
        width="60%"
        class="result_improve_dialog"
      > 

        <!-- 内容 -->
        <avue-form 
          ref="riForm" 
          v-model="riObj" 
          :option="riOption" 
          @submit="confirmResultOrImprove"
        >

          <!-- 相关附件表单自定义 -->
          <template slot="xgfj">
            <div>
              <el-upload
                action="/api/fileManager/upload/file"
                :headers="SetHeaders"
                :file-list="xgfjFileList"
                :before-upload="beforeUploadXGFJ"
                :on-remove="handleRemoveXGFJ"
                :on-success="uploadXGFJSuccess"
              >
                <el-button size="small" type="primary" icon="el-icon-document">选择文件</el-button>
              </el-upload>
            </div>
          </template>

          <!-- 按钮自定义 -->
          <template slot="menuForm">
            <el-button 
              size="small"
              icon="el-icon-close"
              @click="closeResultImproveDialog()">
              取 消
            </el-button>
          </template>

        </avue-form>

      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
import {
  getList,
  add,
  update,
  setRectification
} from "@/api/hiddendangemanage/hiddendangercheck";
import { mapGetters } from "vuex";
import { getDeptTree } from "@/api/system/dept";
import { getToken } from "@/util/auth";
import viewpicture from '../saferisk/components/viewpicture.vue';
import chooseCheckItems from './components/chooseCheckItems.vue';
import {
  optionColumn,
  settingOptionColumn,
  riOptionColumn,
  riOptionGroup
} from "./constant/hiddendangercheck.js";

export default {
  components: { 
    viewpicture,
    chooseCheckItems
  }, 
  data() {
    return {
      form: {},
      query: {},
      data: [],
      loading: true,
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        border: true,
        index: false,
        selection: false,
        viewBtn: true,
        refreshBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        menuWidth: 90,
        column: optionColumn
      },
      // 弹窗：查看图片
      localPicBox: false,
      localPictures: [],
      viewPicTitle: "",
      // 附件
      downloadHead: "/api/fileManager/download/",
      SetHeaders: { "Blade-Auth": getToken() },
      xgfjFileList: [],
      // 弹窗：排查设置
      settingDialog: false,
      settingObj: {},
      selectedTags: [],
      // 弹窗：选择检查项目
      checkItemDialog: false,
      selectedCheckItems: [],
      // 弹窗：排查结果
      riDialogType: "",
      resultStr: "RESULT",
      improveStr: "IMPROVE",
      dialogTitle: "",
      resultImproveDialog: false,
      riObj: {},
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // 按钮权限
    permissionList() {
      return {
        addBtn: false,
        viewBtn: true,
        delBtn: false,
        editBtn: false,
      };
    },

    // 排查设置
    settingOption() {
      return {
        size: "small",
        submitText: "确 定",
        mockBtn: false,
        printBtn: false,
        emptyBtn: false,
        column: settingOptionColumn
      }
    },

    // 排查结果、整改设置
    riOption() {
      return {
        size: "small",
        submitText: "确 定",
        mockBtn: false,
        printBtn: false,
        emptyBtn: false,
        column: riOptionColumn,
        group: riOptionGroup
      }
    }
  },
  mounted() {
    this.initData();
  },
  methods: {

    // 初始化数据
    initData() {
      var tenantId = JSON.parse(localStorage.getItem("saber-tenantId")).content;
      getDeptTree(tenantId).then(res => {
        const sjdxColumn = this.findObject(this.settingOption.column, "sjdx");
        const fzzgbmColumn = this.findObject(this.riOption.group, "fzzgbm");
        sjdxColumn.dicData = res.data.data;
        fzzgbmColumn.dicData = res.data.data;
      }).then(() => {
        this.onLoad(this.page);
      });
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 更换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },

    // 更换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 加载数据
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
    },

    /**
     * 弹窗：图片
    */

    // 查看现场照片
    handleViewPhoto(row) {
      this.localPictures = row.xczpFileList;
      this.localPicBox = true;
      this.viewPicTitle = "现场照片";
    },

    // 确认照片
    confirmViewPicture() {
      this.localPictures = [];
      this.localPicBox = false;
      this.viewPicTitle = "";
    },

    // 关闭弹窗
    handleClosePicBox() {
      this.confirmViewPicture();
    },

    /**
     * 弹窗：排查设置
    */

    // 打开排查设置弹窗
    handleSetting(row) {
      this.settingObj = this.formatSettingObj(row);
      this.selectedTags = row.jcxmList ? row.jcxmList : [];
      this.settingDialog = true;
    },

    // 获取排查设置弹窗所需数据
    formatSettingObj(row) {
      var data = {};
      for(var key in row) {
        data[key] = row[key];
      }
      return data;
    },

    // 关闭选择检查项目tag
    closeSelectedItems(index) {
      this.selectedTags.splice(index, 1);
      this.settingObj.jcxm = this.formatSettingJCXM(this.selectedTags);
    },

    // 获取排查设置中的检查项目值
    formatSettingJCXM(list) {
      var ids = [];
      list.forEach(item => {
        ids.push(item.id);
      });
      return ids.join(",");
    },

    // 确定排查设置
    confirmSetting() {
      this.$refs.settingForm.validate((vaild,done)=>{
        if(vaild){
          var troubleSettingObj = this.formatTroubleSettingObj(this.settingObj);
          if(troubleSettingObj.id === null || troubleSettingObj.id === "" || troubleSettingObj.id === undefined || troubleSettingObj.id < 0) {
            add(troubleSettingObj).then(res => {
              if(res.data.success) {
                this.closeSettingDialog();
                this.page.currentPage = 1;
                this.onLoad(this.page);
              }
            });
          } else {
            update(troubleSettingObj).then(res => {
              if(res.data.success) {
                this.closeSettingDialog();
                this.page.currentPage = 1;
                this.onLoad(this.page);
              }
            });
          }
          done();
        }
      })
    },

    // 获取排查设置所需数据
    formatTroubleSettingObj(row) {
      var data = {};
      var data = {
        jcbt: row.jcbt,
        jlry: row.jlry,
        jhjcrq: row.jhjcrq,
        jczcy: typeof row.jczcy === "object" ? row.jczcy.join(",") : row.jczcy,
        xjry: row.xjry,
        sjdx: row.sjdx,
        jclx: row.jclx,
        jcxm: row.jcxm,
        hiddenDangerInfoId: row.hiddenDangerInfoId
      };
      if(row.id !== "" && row.id !== null && row.id !== undefined && row.id > 0) {
        data["id"] = row.id;
      }
      return data;
    },

    // 关闭、取消排查设置弹窗
    closeSettingDialog() {
      this.settingObj = {};
      this.selectedTags = [];
      this.settingDialog = false;
    },

    /**
     * 弹窗：选择检查项目
    */

    // 打开选择检查项目弹窗
    handleCheck() {
      this.selectedCheckItems = this.selectedTags;
      this.checkItemDialog = true;
    },

    // 确定选择检查项目
    confirmChooseCheckItems(itemList) {
      this.selectedTags = [];
      itemList.forEach(item => {
        this.selectedTags.push({
          id: item.id,
          jcxm: item.jcxm
        });
      });
      this.settingObj.jcxm = this.formatSettingJCXM(this.selectedTags);
      this.closeCheckItemDialog();
    },

    // 关闭、取消选择检查项目弹窗
    closeCheckItemDialog() {
      this.selectedCheckItems = [];
      this.checkItemDialog = false;
    },

    /**
     * 上传相关附件
     */

    // 上传相关附件前
    beforeUploadXGFJ(file) {
      console.log(file);
      var isLimit = this.xgfjFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个相关附件!");
      }
      return isLimit;
    },

    // 上传相关附件成功
    uploadXGFJSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.xgfjFileList = fileList;
      this.riObj.xgfj = this.formatXGFJ(this.xgfjFileList);
    },

    // 删除相关附件
    handleRemoveXGFJ(file, fileList) {
      this.xgfjFileList = fileList;
      this.riObj.xgfj = this.formatXGFJ(this.xgfjFileList);
    },

    // 格式化相关附件ID
    formatXGFJ(fileList) {
      var ids = [];
      fileList.forEach(item => {
        ids.push(item.response.data.id);
      });
      return ids.join(",");
    },

    /**
     * 弹窗：排查结果、整改设置
    */

    // 打开排查结果弹窗
    handleResult(row) {
      this.dialogTitle = "排查结果";
      this.riDialogType = this.resultStr;
      this.riObj = this.formatResultImproveObj(row);
      this.riOption.group[0].display = false;
      this.resultImproveDialog = true;
    },

    // 打开整改设置弹窗
    handleImprove(row) {
      this.dialogTitle = "整改设置";
      this.riDialogType = this.improveStr;
      this.riObj = this.formatResultImproveObj(row);
      this.riOption.group[0].display = true;
      this.xgfjFileList = [];
      if (row.zgxgfjFile && JSON.stringify(row.zgxgfjFile) !== "{}") {
        this.xgfjFileList.push({
          name: row.zgxgfjFile.fileName,
          response: {
            code: 200,
            msg: "操作成功",
            success: true,
            data: row.zgxgfjFile
          }
        });
      }
      this.resultImproveDialog = true;
    },

    // 获取排查结果、整改设置弹窗数据
    formatResultImproveObj(row) {
      var data = {};
      for(var key in row) {
        data[key] = row[key];
      }
      if (row.zgxgfjFile && JSON.stringify(row.zgxgfjFile) !== "{}") {
        data["xgfj"] = row.zgxgfjFile.id;
      }
      return data;
    },

    // 点击确定按钮
    confirmResultOrImprove() {
      if(this.riDialogType === this.resultStr) {
        this.confirmResult();
      } else if(this.riDialogType === this.improveStr) {
        this.confirmImprove();
      }
    },

    // 确定排查结果
    confirmResult() {
      this.closeResultImproveDialog();
    },

    // 确定整改设置
    confirmImprove() {
      this.$refs.riForm.validate((vaild,done)=>{
        if(vaild){
          var improveSettingObj = this.formatImproveSettingObj(this.riObj);
          setRectification(improveSettingObj).then(res => {
            if(res.data.success) {
              this.closeResultImproveDialog();
              this.page.currentPage = 1;
              this.onLoad(this.page);
            }
          });
          done();
        }
      })
    },

    // 获取整改设置所需数据
    formatImproveSettingObj(row) {
      var data = {
        hiddenDangerInfoId: row.hiddenDangerInfoId,
        zgfs: row.zgfs,
        fzzgbm: row.fzzgbm,
        zgfzr: row.zgfzr,
        xgfj: row.xgfj,
        id: row.hdrId
      };
      return data;
    },

    // 关闭、取消排查结果弹窗
    closeResultImproveDialog() {
      this.dialogTitle = "";
      this.riDialogType = "";
      this.riObj = {};
      this.xgfjFileList = [];
      this.resultImproveDialog = false;
    }

  }
};
</script>

<style lang="scss" scpoed>
.hiddendangercheck {
  .avue-crud {
    .avue-crud__search {
      .avue-form__row {
        .el-form-item {
          .el-form-item__label {
            width: 90px !important;
          }

          .el-form-item__content {
            margin-left: 90px !important;
          }
        }
      }
    }
  }

  .ope_row_div {
    .el-button {
      font-size: 12px;
    }
  }

  .enclosure_div {
    a {
      font-size: 12px;
      color: #409eff;

      i {
        margin-right: 5px;
      }
    }
  }
}

.setting_dialog {
  .selected_tag_container {
    .el-tag {
      margin-right: 10px;
    }
  }

  .avue-form__menu--center {
    text-align: center;
  }
}

.result_improve_dialog{
  .avue-form__menu--center {
    text-align: center;
  }
}

.check_item_dialog {
  .avue-crud {
    .avue-crud__menu,
    .avue-crud__pagination {
      display: none;
    }
  }

  .check_item_footer {
    text-align: center;
    margin-top: 15px;

    .el-button {
      width: 100px;
      height: 35px;
    }
  }
}
</style>